package xyz.hzxiao.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import xyz.hzxiao.annotation.Authentication;
import xyz.hzxiao.session.LoginAccountModel;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 权限检查Aop
 *
 * @author ：FuXx
 * @className : cn.miying.aop.AuthenticationAop
 * @since ：2024/5/27
 */
@Aspect
@Component
public class AuthenticationAop {

    @Pointcut(value = "@annotation(xyz.hzxiao.annotation.Authentication)")
    public void controllerMethodPointcut() {
    }

    /**
     * 在切点前检查权限
     *
     * @param pj JoinPoint
     */
    @Before(value = "controllerMethodPointcut()", argNames = "pj")
    public void before(JoinPoint pj) {
        Signature signature = pj.getSignature();
        Method targetMethod = ((MethodSignature) signature).getMethod();
        Authentication apiOperation = targetMethod.getAnnotation(Authentication.class);
//        LoginAccountModel account = UserManager.getCurrentLoginAccount();
        LoginAccountModel account = LoginAccountModel.builder()
                .permissions("1")
                .build();
        Set<String> per = new HashSet<>(Arrays.asList(account.getPermissions().split(",")));
        boolean match = Arrays.stream(apiOperation.value())
                .allMatch(s -> per.contains(s.getValue().toString()));
        Assert.isTrue(match, "你没有此项的操作权限或权限不足");
    }
}
